package com.kdtech.analyse.Answer;

import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.kdtech.crawler.CrawlHTML;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.AnswerMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.HtmlCleaner;
import com.kdtech.utils.StringUtils;
import com.kdtech.analyse.utils.CollectionUtils;
/**
 * http://zhidao.baidu.com/ 百度知道
 * @author allen
 */
public class BaiduanswerAnalyse implements AnalyseAnswer {


	
	public boolean isDetailPage(String url) {
		boolean bRet = false;
		String[] regex = {
				"http://zhidao.baidu.com/question/.*.html.*",
				"https://zhidao.baidu.com/question/[0-9]+.html?fr=qlquick&entry=qb_list_default"
				};
		//https://zhidao.baidu.com/question/1992578169155637107.html?fr=qlquick&entry=qb_list_default
		for (int i = 0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				return true;
			}
		}
		return bRet;
	}

	
	public AnswerMeta parserHtml(UrlMeta urlMeta) {
		AnswerMeta answer = new AnswerMeta();
		if (urlMeta.getHtml() == null) {
		}
		String html = urlMeta.getHtml();
		String url = urlMeta.getUrl();
		if(!isDetailPage(url)){
		}
		answer.setUrl(url);
		String title = null;
		Long date = null;
		Document doc = Jsoup.parse(html);


		title =doc.select("title").text();
        if(title.indexOf("_")!=-1){
    	   title=title.substring(0,title.indexOf("_"));
        }

		if (title!=null && title.equals("百度知道 - 信息提示") || title.equals("信息提示") || title.equals("百度--您的访问出错了")){
			//answer.setUpdateUrl(ParseState.ERR404.toString());
		}
		String tempdate=doc.select("div#wgt-ask div.line span.grid-r").text();
		date = DateUtils.matchDate(tempdate);
		if (date==null){
			date = DateUtils.matchDate(doc.select("div#ask-info").text());
		}
		List<String> answser=new ArrayList<String>();
		Elements select = doc.select("div#body.container div.wgt-best pre.best-text");
		if(select!=null && select.size()!=0){
			for (Element element : select) {
				String html2 = HtmlCleaner.getContentHtml(url,element);
				answser.add(html2);
			}
		}
		Elements select2 = doc.select("div#body.container div.wgt-answers pre.answer-text");
		if(select2!=null && select2.size()!=0){
			for (Element element : select2) {
				String html2 = HtmlCleaner.getContentHtml(url,element);
				answser.add(html2);
			}
		}

		select2 = doc.select("pre.answer-text");
		if(select2!=null && select2.size()!=0){
			for (Element element : select2) {
				String html2 = HtmlCleaner.getContentHtml(url,element);
				answser.add(html2);
			}
		}
		if(date==null){
			date=DateUtils.matchDate(doc.select("div#body.container div.prof-question span.ask-time").text());
		}

		answer.setTitle(StringUtils.trimSpace(title));
		answer.setDate(date);
		answer.setContent(CollectionUtils.join(answser, " "));


		/**
		 * 解析用于更新的地址
		 */
		String updateUrl=null;
		String templastid=null;
		if(url.indexOf("/")!=-1){
			templastid=url.substring(url.lastIndexOf("/")+1);
			if(templastid.indexOf(".")!=-1){
			   templastid=templastid.substring(0,templastid.indexOf("."));
			   updateUrl="http://cp.zhidao.baidu.com/v.php?q="+templastid+"&callback=bd__cbs__gcgvhe";
			   answer.setUpdateUrl(updateUrl);
			   AnswerMeta update=Update(answer);
			   if(update!=null){
				   answer.setClickNum(update.getClickNum());
			   }
			}
		}
		String author=doc.select("div#body.container div#ask-info a.user-name").text();
		if(StringUtils.isBlank(author)){
			author=doc.select("div#body.container div.prof-aside-info p span a").text();
		}
		answer.setAuthor(author);


		return answer;
	}
	
	public AnswerMeta Update(AnswerMeta meta) {
		if(meta!=null){
			String updateUrl = meta.getUpdateUrl();
			if(updateUrl!=null){
				UrlMeta responseToURL = CrawlHTML.responseToURL(updateUrl);
				if(responseToURL!=null){
					String html = responseToURL.getHtml();
					if(html!=null){
						Integer clickNum=0;
					    String clickNumstr=html.replaceAll("bd__cbs__gcgvhe", "");
					    clickNumstr=clickNumstr.replaceAll("\\(", "");
					    clickNumstr=clickNumstr.replaceAll("\\)", "");
					    try {
					    	clickNum=Integer.parseInt(clickNumstr);
						} catch (Exception e) {
							// TODO: handle exception
						}
					    meta.setClickNum(clickNum);
					    return meta;
					}
				}
			}
		}
		return null;
	}
	


	
}
